/*
 * This file is part of Catfish.
 * Copyright (C) 2010 Namazu Studios LLC
 * 
 * Catfish is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as 
 * published by the Free Software Foundation, either version 3 of 
 * the License, or (at your option) any later version.
 * 
 * Catfish is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public
 * License along with Catfish.  If not, please visit:
 *  
 * http://www.gnu.org/licenses/
 *  
 */
package com.namazustudios.catfish.converter;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.lang.reflect.Type;

import com.google.appengine.api.datastore.Blob;
import com.namazustudios.catfish.CatfishException;

public class ObjectSerializer implements Converter<Blob, Serializable> {

    @Override
    public Serializable load(Type cls, Serializable existing, Blob obj) {
        if (obj != null) {
            try {
                ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(obj.getBytes()));
                return (Serializable) ois.readObject();
            } catch (IOException ex) {
                throw new CatfishException(ex.getMessage(), ex);
            } catch (ClassCastException ex) {
                // This should never happen
                throw new CatfishException("Object not instance of Serizable.", ex);
            } catch (ClassNotFoundException ex) {
                throw new CatfishException(ex);
            }
        } else {
            return null;
        }
    }

    @Override
    public Blob store(Serializable obj) {
        if (obj != null) {
            try {
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                ObjectOutputStream oos = new ObjectOutputStream(bos);

                oos.writeObject(obj);

                return new Blob(bos.toByteArray());
            } catch (IOException ex) {
                throw new CatfishException("", ex);
            }
        } else {
            return null;
        }
    }

}
